//
//  HealthFoodListViewController.m
//  LoveHealth
//
//  Created by 枫哥 on 14-9-18.
//  Copyright (c) 2014年 lanou. All rights reserved.
//

#import "HealthFoodListViewController.h"
#import "HealthFoodListTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "HealthFoodDetailViewController.h"
#import "HealthFoodList.h"
#import "MJRefresh.h"
#import "SearchViewController.h"
#import "MONActivityIndicatorView.h"

#import "HealthFoodList.h"

#import "DropdownMenuView.h"
#import "NetHelper.h"
#import "KGStatusBar.h"
@interface HealthFoodListViewController ()<MONActivityIndicatorViewDelegate>

@property(nonatomic,retain)UITableView * tableView;
@property(nonatomic,retain)NSMutableArray * allArray;
@property (nonatomic,assign)NSInteger page;
//声明一个loading用于加载未完成时
@property (nonatomic,retain)MONActivityIndicatorView  * indicatorView;
@property (nonatomic,retain)HealthFoodDetailClass * foodDetailClass;


//下拉菜单
@property (nonatomic,retain)DropdownMenuView  * dmView;
@property (nonatomic, getter = isSelected) BOOL selected;;
@end

@implementation HealthFoodListViewController
- (void)dealloc
{
   
    self.foodDetailClass = nil;
    self.tableView = nil;
    self.allArray = nil;
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    
    self.navigationItem.title = @"健康食谱";
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blueColor];
    self.page = 1;
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds];
    _tableView.rowHeight = 600;
    [self.view addSubview:_tableView];
    
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    [self setupActivityIndicator];
    [self.indicatorView stopAnimating];
    
    [self p_sendReuqest:self.page detailClass:self.foodDetailClass];
    [self setupRefresh];
    
    
    
    UIBarButtonItem * typeButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"list"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone  target:self action:@selector(didClickTypeButtonTtemAction:)];

    UIBarButtonItem * searchButtonTtem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(didClickSearchButtonTtemAction:)];
    
    self.navigationItem.leftBarButtonItem = typeButtonItem;
    self.navigationItem.rightBarButtonItem =searchButtonTtem;
    [typeButtonItem release];
    [searchButtonTtem release];
    
   
    
    
    [self setupDropdownMenu];
    self.allArray = [NSMutableArray array];

}

//设置loading
- (void)setupActivityIndicator
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.delegate = self; //设置代理
    _indicatorView.numberOfCircles = 6; //圆圈个数
    _indicatorView.radius = 10;//圆圈大小
    _indicatorView.internalSpacing = 3;//圆圈之间的间距
    _indicatorView.center = self.view.center;
    
    
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}
//指示器 代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    CGFloat red   = (arc4random() % 256)/255.0;
    CGFloat green = (arc4random() % 256)/255.0;
    CGFloat blue  = (arc4random() % 256)/255.0;
    CGFloat alpha = 1.0f;
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

//下拉菜单
- (void)setupDropdownMenu
{
    CGRect frame = self.view.bounds;
    frame.origin.y -= self.view.bounds.size.height;
    _dmView = [[DropdownMenuView alloc]initWithFrame:frame];
    [self.view addSubview:_dmView];
    //_dmView.delegate = self;
    [_dmView release];
    
    _dmView.hideMenuBlock = ^(HealthFoodDetailClass * detailClass){
        if (detailClass != nil) {
            self.foodDetailClass = detailClass;
            self.page = 1;
            [self p_sendReuqest:self.page detailClass:self.foodDetailClass];
        }
        [self performSelector:@selector(didClickTypeButtonTtemAction:)];
    };
}
- (void)didClickTypeButtonTtemAction:(UIBarButtonItem *)buttonItem
{
    if (!self.selected) {
        self.selected = YES;
        CGRect frame = self.view.bounds;
        frame.origin.y = 64;
        [self.dmView beginShowWithRect:frame];
        
       
    }else{
        self.selected = NO;
        CGRect frame = self.view.bounds;
        frame.origin.y -= self.view.bounds.size.height;
        
        [self.dmView beginShowWithRect:frame];
    }
}

- (void)didClickSearchButtonTtemAction:(UIBarButtonItem *)searchButton
{
    SearchViewController * searchVC = [[SearchViewController alloc]init];
    searchVC.type = foodType;
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}

//下拉刷新，上拉显示更多
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    //[self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在帮你刷新中,不客气";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"正在帮你加载中,不客气";
}

- (void)headerRereshing
{
    
    [self p_sendReuqest:1 detailClass:self.foodDetailClass];
    [self.tableView headerEndRefreshing];
}

- (void)footerRereshing
{
    
    self.page++;
    [self p_sendReuqest:self.page detailClass:self.foodDetailClass];
    [self.tableView reloadData];
    [self.tableView footerEndRefreshing];
}

- (void)p_sendReuqest:(NSInteger )page detailClass:(HealthFoodDetailClass *)detailClass
{
    
    //设置加载loading
    [self.indicatorView startAnimating];
    //拼接网址
    //NSString * urlString =[[NSString alloc]initWithFormat:@"%@?id=%@&page=%ld",APIHealthKnowledgeList,self.knowledgeClass.ID,page];
    NSString * urlString = nil;
    if (detailClass == nil) {
        urlString = [NSString stringWithFormat:@"%@?page=%ld",APIHealthFoodList,page];
    }else{
        urlString = [NSString stringWithFormat:@"%@?page=%ld&id=%@",APIHealthFoodList,page,detailClass.ID];
    }
    
    //设置请求
    //NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    __block HealthFoodListViewController * foodListVC = self;
    //建立异地连接，通过实现block接收数据
    [[NetHelper shareInstance]loadingDataWithUrlString:urlString urlExpireInSeconds:30 download:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        
        if (data != nil && connectionError == nil) {
            if (page == 1) {
                [_allArray removeAllObjects];
            }
            //数据源是个大字典 存到字典中
            NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //        NSArray * array = [dic objectForKey:@"yi18"];
            NSArray * array = dic[@"yi18"];
            
            for (NSDictionary * aDic in array) {
                HealthFoodList * listModel = [[HealthFoodList alloc]init];
                [listModel setValuesForKeysWithDictionary:aDic];
                [_allArray addObject:listModel];
                [listModel release];
                NSLog(@"%@",_allArray);
            }

        }else{
            [KGStatusBar showErrorWithStatus:kNetErrorMessage];
        }
                [_tableView reloadData];
        [foodListVC.indicatorView stopAnimating];
    }];
    
    
    
//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        
//        if (self.allArray ==nil || page == 1) {
//            self.allArray = [NSMutableArray arrayWithCapacity:40];
//        }
//        
//        //数据源是个大字典 存到字典中
//        NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        //        NSArray * array = [dic objectForKey:@"yi18"];
//        NSArray * array = dic[@"yi18"];
//        
//        for (NSDictionary * aDic in array) {
//            HealthFoodList * listModel = [[HealthFoodList alloc]init];
//            [listModel setValuesForKeysWithDictionary:aDic];
//            [_allArray addObject:listModel];
//            [listModel release];
//            NSLog(@"%@",_allArray);
//        }
//        [_tableView reloadData];
//        [foodListVC.indicatorView stopAnimating];
//    }];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * idenfie = @"cell";
    HealthFoodListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:idenfie];
    if (cell == nil) {
        cell = [[[HealthFoodListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idenfie]autorelease];
    }
    
    
    HealthFoodList * foodList = _allArray[indexPath.row];
    
    cell.backgroundColor = [UIColor whiteColor];
    
    cell.nameLabel.text = foodList.name;
    cell.behavierTagLabel.text = foodList.tag;
    NSString * url = APIImageURL(foodList.img);
    [cell.leftImage sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:kPlaceholderImage];
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HealthFoodDetailViewController * foodDetailVC = [[HealthFoodDetailViewController alloc] init];
    
    //属性传值
    HealthFoodList * foodList = _allArray[indexPath.row];
    //NSLog(@"=======%@",foodList);
    HealthFoodListTableViewCell * customcell = (HealthFoodListTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    foodList.showImage = customcell.leftImage.image;
    
    //NSLog(@"33333333333%@",foodList.showImage);
    
    foodDetailVC.foodList = foodList;
    [self.navigationController pushViewController:foodDetailVC animated:YES];
    [foodDetailVC release];
}

//- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    cell.frame = CGRectMake(-320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
//    [UIView animateWithDuration:0.7 animations:^{
//        cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
//    } completion:^(BOOL finished) {
//        ;
//    }];
//}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
